package com.ha7419x.service.impl;

import com.ha7419x.common.Constant;
import com.ha7419x.dto.FlowNodeStructure;
import com.ha7419x.exception.BizException;
import com.ha7419x.service.FlowNodeService;
import com.ha7419x.vo.Result;
import lombok.SneakyThrows;
import org.apache.logging.log4j.util.Strings;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.util.*;
import java.util.function.Function;
import java.util.stream.Collectors;

@Service
public class FlowNodeServiceImpl implements FlowNodeService {
    @SneakyThrows
    @Override
    public Result flowNodeAdd(List<FlowNodeStructure> nodeDtoList) {
        if (CollectionUtils.isEmpty(nodeDtoList)) {
            return new Result("节点为空");
        }
        // 1. 获取开始节点
        List<FlowNodeStructure> startNodeList = buildParentChild(nodeDtoList);
        if (CollectionUtils.isEmpty(startNodeList)) {
            return new Result("没有开始节点");
        }
        if (startNodeList.size() > 1) {
            return new Result("开始节点存在多个");
        }
        Map<String, Map<String, List<String>>> cameraAlgoAreaMap = new HashMap<>(0); //TODO 从相机算法却表中获取数据
        List<FlowNodeStructure> endNodeList = new ArrayList<>();
        // 从开始节点验证每个节点是否合规
        startNodeList.get(0).verification(cameraAlgoAreaMap, new ArrayList<>(), endNodeList);
        if (endNodeList.size() > 1) {
            return new Result("存在多个结束节点");
        }
        return Result.ok();
    }

    /**
     * 构建父-子关系的双向链表
     * @param nodeDtoList   原始数据
     * @return              开始节点List
     */
    private List<FlowNodeStructure> buildParentChild(List<FlowNodeStructure> nodeDtoList) throws BizException{
        Map<String, FlowNodeStructure> flowNodeMap = nodeDtoList.stream()
                .collect(Collectors.toMap(FlowNodeStructure::getId, Function.identity(), (key1, key2) -> key2));
        List<FlowNodeStructure> startNodeList = new ArrayList<>();
        for (FlowNodeStructure node: nodeDtoList) {
            if (Strings.isBlank(node.getPid())) {
                startNodeList.add(node);
                continue;
            }
            List<String> pidList = Arrays.asList(node.getPid().split(Constant.COMMA));
            for (String pid: pidList) {
                FlowNodeStructure parentNode = flowNodeMap.get(pid);
                if (Objects.isNull(parentNode)) {
                    throw new BizException(String.format("【%s】父节不存在", node.getNodeName()));
                }
                parentNode.addChildNode(node);
                node.addParentNode(parentNode);
            }
        }
        return startNodeList;
    }
}
